package db

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/redis/go-redis/v9"
)

// RedisConfig Redis数据库配置
type RedisConfig struct {
	Host     string
	Port     int
	Password string
	DB       int
	PoolSize int
}

// DefaultRedisConfig 默认Redis配置
func DefaultRedisConfig() RedisConfig {
	return RedisConfig{
		Host:     "localhost",
		Port:     6379,
		Password: "",
		DB:       0,
		PoolSize: 10,
	}
}

var (
	// RedisClient 全局Redis客户端
	RedisClient *redis.Client
	// RedisCtx Redis上下文
	RedisCtx = context.Background()
)

// InitRedis 初始化Redis连接
func InitRedis(config RedisConfig) error {
	client := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", config.Host, config.Port),
		Password: config.Password,
		DB:       config.DB,
		PoolSize: config.PoolSize,
	})

	// 测试连接
	ctx, cancel := context.WithTimeout(RedisCtx, 5*time.Second)
	defer cancel()

	status := client.Ping(ctx)
	if status.Err() != nil {
		return fmt.Errorf("Redis连接测试失败: %w", status.Err())
	}

	RedisClient = client
	log.Println("Redis连接成功")
	return nil
}

// CloseRedisConnection 关闭Redis连接
func CloseRedisConnection() {
	if RedisClient != nil {
		if err := RedisClient.Close(); err != nil {
			log.Printf("关闭Redis连接时发生错误: %v", err)
		} else {
			log.Println("Redis连接已关闭")
		}
	}
}
